<?php

class AEngine {

  /**
   * @var app
   */
  protected static $_inst;

  /**
   * @return app
   */
  public static function getInst() {
    if (self::$_inst == NULL) {
      self::$_inst = new self();
    }
    return self::$_inst;
  }

  /**
   * process the request
   */
  public function process() {
    @$uri = $_SERVER['REDIRECT_URL'] ? $_SERVER['REDIRECT_URL'] : $_SERVER['REQUEST_URI'];
    $uri = str_replace(BASE_URI, '', $uri);
    @list ($action_name, $args) = Router::match($uri);
    $class_name = str_replace('.', '_', $action_name);

    $action = new $class_name($args);

    $method_name = 'do' . (@$_SERVER['REQUEST_METHOD'] == 'POST' ? 'Post' : 'Get') . (@$_SERVER['HTTP_X_REQUESTED_WITH'] ? 'Async' : '');
    $action->{$method_name}($args);
    echo $action->render();
  }

  /**
   * @param  int $length
   * @return string
   */
  public static function getRandomString($length=8) {
    $seek = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $string = '';
    for ($i = 0; $i < $length; ++$i) {
      $string .= $seek[mt_rand(0, 51)];
    }
    return $string;
  }

}